<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>聊天页面</title>
  <script src="/js/jquery-3.5.1.js"></script>
  <script src="/js/jquery-3.6.0.min.js"></script>
  <link href="/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .chat-box {
      height: 600px;
      overflow-y: auto;
      border: 1px solid #ddd;
      padding: 10px;
      background-color: #f9f9f9;
    }
    .chat-message {
      margin-bottom: 10px;
    }
    .chat-message.user {
      text-align: right;
      color: blue;
    }
    .chat-message.assistant {
      text-align: left;
      color: green;
    }
    .session-list {
      height: 600px;
      overflow-y: auto;
      border: 1px solid #ddd;
      background-color: #fff;
    }
    .session-item {
      cursor: pointer;
      padding: 10px;
      border-bottom: 1px solid #eee;
    }
    .session-item.active {
      background-color: #e6f7ff;
    }
  </style>
</head>
<body>
<div class="container-fluid mt-3">
  <div class="row">
    <!-- 左侧会话列表 -->
    <div class="col-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h4 class="mb-0">会话列表</h4>
        <button class="btn btn-sm btn-success" id="addSessionBtn">添加会话</button>
      </div>
      <div class="session-list" id="sessionList"></div>
    </div>


    <!-- 右侧聊天窗口 -->
    <div class="col-9">
      <h4 id="sessionTitle">聊天窗口</h4>
      <div class="chat-box mb-3" id="chatBox"></div>
      <div class="input-group">
        <input type="text" class="form-control" id="userInput" placeholder="请输入消息">
        <button class="btn btn-primary" id="sendBtn">发送</button>
      </div>
    </div>
  </div>
</div>

<script src="/js/chat.js"></script>
</body>


<script type="text/javascript">
    let sessions = [];
    let activeSessionId = null; //会话ID
    let chatAssistantId = "9ec7ae4a50c711f087da8a1354407bfd"; //聊天助手ID
    $(document).ready(function () {

        // let chatAssistantId = null;
        // 这里先默认写死

        // 进入页面创建 聊天助手
        // 这里可以添加了，先注释，调用时再放开
        // $.ajax({
        //     url:"/ragFlow/chatAssistant/add",
        //     type: "POST",
        //     data: {name:"Java测试聊天助手"},
        //     success: function (data){
        //         chatAssistantId = data.id;
        //         console.log(data);
        //         console.log("创建成功，chatAssistantId：", chatAssistantId);
        //     },
        //     error: function (data){
        //         console.log(data.message);
        //     }
        // })


        // 刚开始进入页面根据 聊天助手创建的 展示聊天助手下的 聊天会话
        $.ajax({
            url: "/ragFlow/chat/list",
            type: "GET",
            data: { chatId: chatAssistantId },
            success: function (res) {
                if (res.code === 0) {
                    sessions = res.data;
                    renderSessionList();
                    if (sessions.length > 0) {
                      loadSession(sessions[0].id);
                    }
                }
            },
            error: function () {
              alert("请求失败，请检查服务器！");
            }
        });


        $("#sendBtn").click(function () {
            sendMessage();
        });

        $("#userInput").keypress(function (e) {
            if (e.which === 13) {
                sendMessage();
            }
        });
    });


  function renderSessionList() {
    let html = '';
    sessions.forEach(item => {
      html += `<div class="session-item" data-id="${item.id}">${item.name}</div>`;
    });
    $("#sessionList").html(html);

    console.log("renderSessionList方法中的 sessionID："+$(this).data("id"));

    $(".session-item").click(function () {
      $(".session-item").removeClass("active");
      $(this).addClass("active");
      let id = $(this).data("id");
      loadSession(id);
    });
  }

    function loadSession(sessionId) {
      activeSessionId = sessionId;
      let session = sessions.find(s => s.id === sessionId);
      $("#sessionTitle").text(session.name);
      renderChat(session.messages);
    }

    function renderChat(messages) {
      let html = '';
      messages.forEach(msg => {
        html += `<div class="chat-message ${msg.role}">${msg.role === 'user' ? '用户' : '助手'}：${msg.content}</div>`;
      });
      $("#chatBox").html(html);
      $("#chatBox").scrollTop($("#chatBox")[0].scrollHeight);
    }

    function sendMessage() {
      let input = $("#userInput").val().trim();
      if (input === "") return;

      let session = sessions.find(s => s.id === activeSessionId);
      if (!session) return;

      // 先显示用户消息
      session.messages.push({ role: "user", content: input });
      renderChat(session.messages);
      $("#userInput").val("");

      let url = `/ragFlow/chat/chatStream?question=${encodeURIComponent(input)}&sessionId=${activeSessionId}&chatId=${chatAssistantId}`;
      let eventSource = new EventSource(url);

      let assistantMessage = { role: "assistant", content: "" };
      session.messages.push(assistantMessage); // 添加助手气泡，内容逐步填充
      renderChat(session.messages);

      eventSource.onmessage = function (event) {
        console.log("流式响应：", event.data);

        assistantMessage.content += event.data; // 拼接内容
        renderChat(session.messages);
      };

      eventSource.onerror = function (event) {
        console.error("流式出错：", event);

        // 这里可以等待一段时间，或者尝试重连
        setTimeout(() => {
          console.log("尝试保持连接或自动重连...");
          // 也可以设计重连逻辑
        }, 10000);

        if (eventSource.readyState === EventSource.CLOSED || event.eventPhase === EventSource.CLOSED) {
          console.log("连接已关闭，主动断开");
          eventSource.close();
        }
      };
    }


    //添加会话
    $("#addSessionBtn").click(
            function () {
              let sessionName = prompt("请输入新会话名称：");
              if (!sessionName) {
                return; // 用户取消或输入为空，不执行
              }
              //添加会话的ajax
              $.ajax({
                url: "/ragFlow/chat/add",
                type: "POST",
                data: {chatId : chatAssistantId,name: sessionName},
                success: function (data) {
                   console.log("添加会话成功"+JSON.stringify(data))
                   activeSessionId = data.id;
                   //刷新 左侧列表
                  $.ajax({
                    url: "/ragFlow/chat/list",
                    type: "GET",
                    data: {chatId: chatAssistantId},
                    success: function (res) {
                      if (res.code === 0) {
                        sessions = res.data;
                        renderSessionList();
                        if (sessions.length > 0) {
                          loadSession(sessions[sessions.length - 1].id); // 自动选中新添加的会话
                        }
                      }
                    },
                    error: function () {
                      alert("刷新会话失败！");
                    }
                  })
                }

              });
            }
            
    )


</script>
</html>
